import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import JSEncrypt from 'jsencrypt'
import request from '../../api/request'

const publicKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuQd3gESx7VdIyRYUWjmjg61VIgUK6F45hClmqUMZ7xNiT5rlLM6e78osMvBF/yP7cVm7pK+NMCDWoVS1/AETpxJYqUlIC77ZAU8/MnP96IupnJL87vqhPcpdv7+VqLM38ls++yuD/F/HSoOQTv/leJh+dgE/4EYAJjOWFAbYfXwIDAQAB`

interface LoginResponseResult {
  sessionId?: string
  userId?: number
  [key: string]: unknown
}

interface ApiResponse<T> {
  result: T
  message: string
  status: string
}

const Login = () => {
  const navigate = useNavigate()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    console.log('eeeeeeeeeee', e);

    e.preventDefault()
    if (!email || !password) {
      alert('请输入邮箱和密码')
      return
    }
    setLoading(true)
    try {
      const encryptor = new JSEncrypt()
      const pemPublicKey = `-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`
      encryptor.setPublicKey(pemPublicKey)
      const encryptedPwd = encryptor.encrypt(password)
      if (!encryptedPwd) {
        throw new Error('密码加密失败')
      }

      const form = new URLSearchParams()
      form.set('email', email)
      form.set('pwd', encryptedPwd)

      const res = (await request.post('/health/user/v1/login', form, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
      })) as ApiResponse<LoginResponseResult>

      if (res.status === '0000') {
        const sessionId = res.result?.sessionId || ''
        const userId = res.result?.userId
        if (sessionId) {
          // 与全局拦截器保持一致，使用 token 键保存
          localStorage.setItem('token', sessionId)
          // 额外单独存储，便于其他地方直接读取
          localStorage.setItem('sessionId', sessionId)
        }
        if (typeof userId !== 'undefined') {
          localStorage.setItem('userId', String(userId))
        }
        alert('登录成功')
        navigate(-1)
      } else {
        alert(res.message || '登录失败')
      }
    } catch (error: any) {
      console.error('登录请求失败:', error?.response?.status, error?.response?.data || error)
      const msg = error?.response?.data?.message || error?.message || '登录失败，请稍后重试'
      alert(msg)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ padding: 24 }}>
      <h3>登录</h3>
      <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 360 }}>
        <input
          type="email"
          placeholder="邮箱"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
          style={{ height: 36, padding: '0 10px', borderRadius: 6, border: '1px solid #ddd' }}
        />
        <input
          type="password"
          placeholder="密码（将进行加密）"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
          style={{ height: 36, padding: '0 10px', borderRadius: 6, border: '1px solid #ddd' }}
        />
        <button type="submit" disabled={loading} style={{ height: 40, borderRadius: 6 }}>
          {loading ? '登录中...' : '登录'}
        </button>
      </form>
    </div>
  )
}

export default Login
